from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse

from myadmin.models import Member
from myadmin.models import Shop
from myadmin.models import Category
from myadmin.models import Product

# Create your views here.
def index(request):
    '''移动端首页'''
    #尝试从session中获取店铺信息
    shopinfo = request.session.get("shopinfo",None)
    #判断是否没有选择店铺，跳转去选择
    if shopinfo is None:
        return redirect(reverse('mobile_shop'))
    #获取当前店铺下所有的菜品信息
    clist = Category.objects.filter(shop_id=shopinfo['id'],status=1)
    productlist = dict()
    for vo in clist:
        plist = Product.objects.filter(shop_id=shopinfo['id'],category_id=vo.id,status=1)
        productlist[vo.id] = plist
    context = {"shopinfo":shopinfo,"categorylist":clist,"productlist":productlist.items(),"cid":clist[0]}
    return render(request,"mobile/index.html",context)

def register(request):
    '''加载注册/登录页面'''
    return render(request,"mobile/register.html")

def doregister(request):
    '''执行注册/登录'''
     #验证短信码
    verifycode = "1234" #request.session['verifycode']
    code = request.POST['code']
    if verifycode != code:
        context = {'info':'验证码错误！'}
        return render(request,"mobile/register.html",context)

    try:
        #根据登录手机号码获取会员信息
        member = Member.objects.get(mobile=request.POST['mobile'])
        # 校验当前用户状态是否是管理员
        if member.status == 1:
            # 将当前登录成功用户信息以adminuser这个key放入到session中
            request.session['mobileuser']=member.toDict()
            return redirect(reverse('mobile_index'))
        else:
            context={"info":"此用户账号非正常账号！"}
    except Exception as err:
        print(err)
        context={"info":"登录账号不存在！"}
    return render(request,"mobile/register.html",context)
    #return redirect(reverse('mobile_shop'))

def shop(request):
    ''' 呈现店铺选择页面 '''
    context = {'shoplist':Shop.objects.filter(status__lt=9)}
    return render(request,"mobile/shop.html",context)

def selectShop(request):
    ''' 执行店铺选择 '''
    #获取店铺id号，通过店铺id号获取店铺信息
    sid = request.GET['sid']
    ob = Shop.objects.get(id=sid) 
    #将店铺信息放入到session中
    request.session['shopinfo'] = ob.toDict()
    return redirect(reverse('mobile_index'))

def addOrders(request):
    cartlist = request.session.get("cartlist",{})
    return render(request,"mobile/addOrders.html",{"cartlist":cartlist.items()})